package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();

    @Override
    public List<User> findAll() {
        return dao.findAll();
    }

    @Override
    public User login(User user) {
        return dao.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());

    }

    @Override
    public void addUser(User user) {
        dao.AddUser(user);
    }

    @Override
    public void delUser(String id) {
        dao.delUser(Integer.parseInt(id));
    }

    @Override
    public User findUser(String id) {
        return dao.findUser(Integer.parseInt(id));
    }

    @Override
    public void update(User user) {
        dao.update(user);
    }

    @Override
    public void delSelected(String[] ids) {
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                dao.delUser(Integer.parseInt(id));
            }
        }
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);
        //健壮性判断，防止用户在第一页点击上一页
        if (currentPage <= 0) {
            currentPage = 1;
        }
        //1.创建空的PageBean对象
        PageBean<User> pb = new PageBean<User>();
        //2.设置参数
        pb.setCurrentPage(currentPage); //设置当前页码
        pb.setRows(rows);   //设置每页显示的记录数

        //3.调用dao查询总记录数
//        int totalCount = dao.findTotalCount();
        //改造成分页条件查询
        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);//设置总记录数

        //5.计算总页码
        int totalPage = totalCount % rows == 0 ? totalCount / rows : totalCount / rows + 1;
        pb.setTotalPage(totalPage); //设置总页码
        //健壮性判断，防止用户在最后一页点击下一页
        if (currentPage >= totalPage) {
            currentPage = totalPage;
        }

        //4.调用dao查询List集合
        //计算开始的记录索引
        int start = (currentPage - 1) * rows;
//        List<User> list = dao.findByPage(start, rows);

        //改造成分页条件查询
        List<User> list = dao.findByPage(start, rows, condition);
        pb.setList(list);   //设置每页的数据

        //6.返回PageBean对象
        return pb;
    }
}
